"""
会话和消息模型
"""
from sqlalchemy import Column, String, Text, Integer, ForeignKey, Enum, Float
from sqlalchemy.orm import relationship
from enum import Enum as PyEnum
from .base import BaseModel


class MessageType(PyEnum):
    """消息类型枚举"""
    USER = "user"
    ASSISTANT = "assistant"
    SYSTEM = "system"


class ChatSession(BaseModel):
    """聊天会话模型"""
    __tablename__ = "chat_sessions"
    
    session_id = Column(String(100), unique=True, index=True, nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    title = Column(String(200), nullable=True)
    system_context = Column(Text, nullable=True)  # 系统上下文信息
    is_active = Column(String(10), default="active")  # active, completed, archived
    
    # 关联关系
    user = relationship("User", back_populates="chat_sessions")
    messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<ChatSession(session_id='{self.session_id}', title='{self.title}')>"


class ChatMessage(BaseModel):
    """聊天消息模型"""
    __tablename__ = "chat_messages"
    
    session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False)
    message_type = Column(Enum(MessageType), nullable=False)
    content = Column(Text, nullable=False)
    message_metadata = Column(Text, nullable=True)  # JSON格式的元数据
    confidence_score = Column(Float, nullable=True)  # AI回答的置信度
    operation_id = Column(Integer, ForeignKey("operation_documents.id"), nullable=True)
    
    # 关联关系
    session = relationship("ChatSession", back_populates="messages")
    operation = relationship("OperationDocument", back_populates="messages")
    
    def __repr__(self):
        return f"<ChatMessage(type='{self.message_type}', content='{self.content[:50]}...')>"
